package wendu.dsbridge;

import static android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Keep;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.PermissionRequest;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebStorage;
import com.tencent.smtt.sdk.WebView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * Created by du on 16/12/29.
 */

public class DWebView extends WebView {
    private static final String BRIDGE_NAME = "_dsbridge";
    private static final String LOG_TAG = "dsBridge";
    private static boolean isDebug = false;
    private Map<String, Object> javaScriptNamespaceInterfaces = new HashMap();
    private String APP_CACHE_DIRNAME;
    int callID = 0;
    private WebChromeClient webChromeClient;
    private volatile boolean alertBoxBlock = true;
    private JavascriptCloseWindowListener javascriptCloseWindowListener = null;
    private ArrayList<CallInfo> callInfoList;
    private InnerJavascriptInterface innerJavascriptInterface = new InnerJavascriptInterface();
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    Map<Integer, OnReturnValue> handlerMap = new HashMap();
    private WebChromeClient mWebChromeClient;

    public DWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mWebChromeClient = new DWebChromeClient();
        this.init();
    }

    public DWebView(Context context) {
        this(context, null);
    }

    public static void setWebContentsDebuggingEnabled(boolean enabled) {
        if (Build.VERSION.SDK_INT >= 19) {
            WebView.setWebContentsDebuggingEnabled(enabled);
        }

        isDebug = enabled;
    }

    class DWebChromeClient extends WebChromeClient {

        public void onProgressChanged(WebView view, int newProgress) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onProgressChanged(view, newProgress);
            } else {
                super.onProgressChanged(view, newProgress);
            }

        }

        public void onReceivedTitle(WebView view, String title) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onReceivedTitle(view, title);
            } else {
                super.onReceivedTitle(view, title);
            }
        }

        @Override
        public void onPermissionRequest(PermissionRequest permissionRequest) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onPermissionRequest(permissionRequest);
            } else {
                super.onPermissionRequest(permissionRequest);
            }
        }

        @Override
        public void onPermissionRequestCanceled(PermissionRequest permissionRequest) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onPermissionRequestCanceled(permissionRequest);
            } else {
                super.onPermissionRequestCanceled(permissionRequest);
            }
        }

        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onReceivedIcon(view, icon);
            } else {
                super.onReceivedIcon(view, icon);
            }

        }

        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onReceivedTouchIconUrl(view, url, precomposed);
            } else {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }

        }

        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onShowCustomView(view, callback);
            } else {
                super.onShowCustomView(view, callback);
            }

        }

        public void onShowCustomView(View view, int requestedOrientation, IX5WebChromeClient.CustomViewCallback callback) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onShowCustomView(view, requestedOrientation, callback);
            } else {
                super.onShowCustomView(view, requestedOrientation, callback);
            }

        }

        public void onHideCustomView() {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onHideCustomView();
            } else {
                super.onHideCustomView();
            }

        }

        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            return DWebView.this.webChromeClient != null ? DWebView.this.webChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg) : super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        }

        public void onRequestFocus(WebView view) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onRequestFocus(view);
            } else {
                super.onRequestFocus(view);
            }

        }

        public void onCloseWindow(WebView window) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onCloseWindow(window);
            } else {
                super.onCloseWindow(window);
            }

        }

        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            if (!DWebView.this.alertBoxBlock) {
                result.confirm();
            }

            if (DWebView.this.webChromeClient != null && DWebView.this.webChromeClient.onJsAlert(view, url, message, result)) {
                return true;
            } else {
                Dialog alertDialog = (new AlertDialog.Builder(DWebView.this.getContext())).setMessage(message).setCancelable(false).setPositiveButton(17039370, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (DWebView.this.alertBoxBlock) {
                            result.confirm();
                        }

                    }
                }).create();
                alertDialog.show();
                return true;
            }
        }

        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            if (!DWebView.this.alertBoxBlock) {
                result.confirm();
            }

            if (DWebView.this.webChromeClient != null && DWebView.this.webChromeClient.onJsConfirm(view, url, message, result)) {
                return true;
            } else {
                DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (DWebView.this.alertBoxBlock) {
                            if (which == -1) {
                                result.confirm();
                            } else {
                                result.cancel();
                            }
                        }

                    }
                };
                (new AlertDialog.Builder(DWebView.this.getContext())).setMessage(message).setCancelable(false).setPositiveButton(17039370, listener).setNegativeButton(17039360, listener).show();
                return true;
            }
        }

        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
            if (Build.VERSION.SDK_INT <= 16) {
                String prefix = "_dsbridge=";
                if (message.startsWith(prefix)) {
                    result.confirm(DWebView.this.innerJavascriptInterface.call(message.substring(prefix.length()), defaultValue));
                    return true;
                }
            }

            if (!DWebView.this.alertBoxBlock) {
                result.confirm();
            }

            if (DWebView.this.webChromeClient != null && DWebView.this.webChromeClient.onJsPrompt(view, url, message, defaultValue, result)) {
                return true;
            } else {
                final EditText editText = new EditText(DWebView.this.getContext());
                editText.setText(defaultValue);
                if (defaultValue != null) {
                    editText.setSelection(defaultValue.length());
                }

                float dpi = DWebView.this.getContext().getResources().getDisplayMetrics().density;
                DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (DWebView.this.alertBoxBlock) {
                            if (which == -1) {
                                result.confirm(editText.getText().toString());
                            } else {
                                result.cancel();
                            }
                        }

                    }
                };
                (new AlertDialog.Builder(DWebView.this.getContext())).setTitle(message).setView(editText).setCancelable(false).setPositiveButton(17039370, listener).setNegativeButton(17039360, listener).show();
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(-1, -2);
                int t = (int) (dpi * 16.0F);
                layoutParams.setMargins(t, 0, t, 0);
                layoutParams.gravity = 1;
                editText.setLayoutParams(layoutParams);
                int padding = (int) (15.0F * dpi);
                editText.setPadding(padding - (int) (5.0F * dpi), padding, padding, padding);
                return true;
            }
        }

        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            return DWebView.this.webChromeClient != null ? DWebView.this.webChromeClient.onJsBeforeUnload(view, url, message, result) : super.onJsBeforeUnload(view, url, message, result);
        }

        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
            } else {
                super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
            }

        }

        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            }

            super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
        }

        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissionsCallback callback) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onGeolocationPermissionsShowPrompt(origin, callback);
            } else {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

        }

        public void onGeolocationPermissionsHidePrompt() {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.onGeolocationPermissionsHidePrompt();
            } else {
                super.onGeolocationPermissionsHidePrompt();
            }

        }

        public boolean onJsTimeout() {
            return DWebView.this.webChromeClient != null ? DWebView.this.webChromeClient.onJsTimeout() : super.onJsTimeout();
        }

        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            return DWebView.this.webChromeClient != null ? DWebView.this.webChromeClient.onConsoleMessage(consoleMessage) : super.onConsoleMessage(consoleMessage);
        }

        public Bitmap getDefaultVideoPoster() {
            return DWebView.this.webChromeClient != null ? DWebView.this.webChromeClient.getDefaultVideoPoster() : super.getDefaultVideoPoster();
        }

        public View getVideoLoadingProgressView() {
            return DWebView.this.webChromeClient != null ? DWebView.this.webChromeClient.getVideoLoadingProgressView() : super.getVideoLoadingProgressView();
        }

        public void getVisitedHistory(ValueCallback<String[]> callback) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.getVisitedHistory(callback);
            } else {
                super.getVisitedHistory(callback);
            }

        }

        public void openFileChooser(ValueCallback<Uri> valueCallback, String s, String s1) {
            if (DWebView.this.webChromeClient != null) {
                DWebView.this.webChromeClient.openFileChooser(valueCallback, s, s1);
            } else {
                super.openFileChooser(valueCallback, s, s1);
            }
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            return DWebView.this.webChromeClient != null ? DWebView.this.webChromeClient.onShowFileChooser(webView, filePathCallback, fileChooserParams) : super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
        }

        @Keep
        @TargetApi(11)
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            if (DWebView.this.webChromeClient instanceof FileChooser) {
                ((FileChooser) DWebView.this.webChromeClient).openFileChooser(valueCallback, acceptType);
            }

        }
    }

    @Keep
    private void init() {
        this.APP_CACHE_DIRNAME = this.getContext().getFilesDir().getAbsolutePath() + "/webcache";
        WebSettings settings = this.getSettings();
        settings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= 21) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(this, true);
            settings.setMixedContentMode(0);
        }

        settings.setAllowFileAccess(false);
        settings.setAppCacheEnabled(false);
        settings.setCacheMode(2);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setAppCachePath(this.APP_CACHE_DIRNAME);
        settings.setUseWideViewPort(true);
        super.setWebChromeClient(this.mWebChromeClient);
        this.addInternalJavascriptObject();
        if (Build.VERSION.SDK_INT > 16) {
            super.addJavascriptInterface(this.innerJavascriptInterface, "_dsbridge");
        } else {
            settings.setUserAgentString(settings.getUserAgentString() + " _dsbridge");
        }

    }

    private String[] parseNamespace(String method) {
        int pos = method.lastIndexOf(46);
        String namespace = "";
        if (pos != -1) {
            namespace = method.substring(0, pos);
            method = method.substring(pos + 1);
        }

        return new String[]{namespace, method};
    }

    @Keep
    private void addInternalJavascriptObject() {
        this.addJavascriptObject(new Object() {
            @JavascriptInterface
            @Keep
            public boolean hasNativeMethod(Object args) throws JSONException {
                JSONObject jsonObject = (JSONObject) args;
                String methodName = jsonObject.getString("name").trim();
                String type = jsonObject.getString("type").trim();
                String[] nameStr = DWebView.this.parseNamespace(methodName);
                Object jsb = DWebView.this.javaScriptNamespaceInterfaces.get(nameStr[0]);
                if (jsb != null) {
                    Class<?> cls = jsb.getClass();
                    boolean asyn = false;
                    Method method = null;

                    try {
                        method = cls.getMethod(nameStr[1], Object.class, CompletionHandler.class);
                        asyn = true;
                    } catch (Exception var13) {
                        try {
                            method = cls.getMethod(nameStr[1], Object.class);
                        } catch (Exception var12) {
                        }
                    }

                    if (method != null) {
                        JavascriptInterface annotation = (JavascriptInterface) method.getAnnotation(JavascriptInterface.class);
                        if (annotation != null && ("all".equals(type) || asyn && "asyn".equals(type) || !asyn && "syn".equals(type))) {
                            return true;
                        }
                    }
                }

                return false;
            }

            @JavascriptInterface
            @Keep
            public String closePage(Object object) throws JSONException {
                DWebView.this.runOnMainThread(new Runnable() {
                    public void run() {
                        if (DWebView.this.javascriptCloseWindowListener == null || DWebView.this.javascriptCloseWindowListener.onClose()) {
                            Context context = DWebView.this.getContext();
                            if (context instanceof Activity) {
                                ((Activity) DWebView.this.getContext()).onBackPressed();
                            }
                        }

                    }
                });
                return null;
            }

            @JavascriptInterface
            @Keep
            public void disableJavascriptDialogBlock(Object object) throws JSONException {
                JSONObject jsonObject = (JSONObject) object;
                DWebView.this.alertBoxBlock = !jsonObject.getBoolean("disable");
            }

            @JavascriptInterface
            @Keep
            public void dsinit(Object jsonObject) {
                DWebView.this.dispatchStartupQueue();
            }

            @JavascriptInterface
            @Keep
            public void returnValue(final Object obj) throws JSONException {
                DWebView.this.runOnMainThread(new Runnable() {
                    public void run() {
                        JSONObject jsonObject = (JSONObject) obj;
                        Object data = null;

                        try {
                            int id = jsonObject.getInt("id");
                            boolean isCompleted = jsonObject.getBoolean("complete");
                            OnReturnValue handler = (OnReturnValue) DWebView.this.handlerMap.get(id);
                            if (jsonObject.has("data")) {
                                data = jsonObject.get("data");
                            }

                            if (handler != null) {
                                handler.onValue(data);
                                if (isCompleted) {
                                    DWebView.this.handlerMap.remove(id);
                                }
                            }
                        } catch (JSONException var6) {
                            var6.printStackTrace();
                        }

                    }
                });
            }
        }, "_dsb");
    }

    private void _evaluateJavascript(String script) {
        if (Build.VERSION.SDK_INT >= 19) {
            super.evaluateJavascript(script, (ValueCallback) null);
        } else {
            super.loadUrl("javascript:" + script);
        }

    }

    public void evaluateJavascript(final String script) {
        this.runOnMainThread(new Runnable() {
            public void run() {
                DWebView.this._evaluateJavascript(script);
            }
        });
    }

    public void loadUrl(final String url) {
        this.runOnMainThread(new Runnable() {
            public void run() {
                DWebView.this.callInfoList = new ArrayList();
                DWebView.super.loadUrl(url);
            }
        });
    }

    public void loadUrl(final String url, final Map<String, String> additionalHttpHeaders) {
        this.runOnMainThread(new Runnable() {
            public void run() {
                DWebView.this.callInfoList = new ArrayList();
                DWebView.super.loadUrl(url, additionalHttpHeaders);
            }
        });
    }

    public void reload() {
        this.runOnMainThread(new Runnable() {
            public void run() {
                DWebView.this.callInfoList = new ArrayList();
                DWebView.super.reload();
            }
        });
    }

    public void setJavascriptCloseWindowListener(JavascriptCloseWindowListener listener) {
        this.javascriptCloseWindowListener = listener;
    }

    private synchronized void dispatchStartupQueue() {
        if (this.callInfoList != null) {
            Iterator var1 = this.callInfoList.iterator();

            while (var1.hasNext()) {
                CallInfo info = (CallInfo) var1.next();
                this.dispatchJavascriptCall(info);
            }

            this.callInfoList = null;
        }

    }

    private void dispatchJavascriptCall(CallInfo info) {
        this.evaluateJavascript(String.format("window._handleMessageFromNative(%s)", info.toString()));
    }

    public synchronized <T> void callHandler(String method, Object[] args, OnReturnValue<T> handler) {
        CallInfo callInfo = new CallInfo(method, this.callID++, args);
        if (handler != null) {
            this.handlerMap.put(callInfo.callbackId, handler);
        }

        if (this.callInfoList != null) {
            this.callInfoList.add(callInfo);
        } else {
            this.dispatchJavascriptCall(callInfo);
        }

    }

    public void callHandler(String method, Object[] args) {
        this.callHandler(method, args, (OnReturnValue) null);
    }

    public <T> void callHandler(String method, OnReturnValue<T> handler) {
        this.callHandler(method, (Object[]) null, handler);
    }

    public void hasJavascriptMethod(String handlerName, OnReturnValue<Boolean> existCallback) {
        this.callHandler("_hasJavascriptMethod", new Object[]{handlerName}, existCallback);
    }

    public void addJavascriptObject(Object object, String namespace) {
        if (namespace == null) {
            namespace = "";
        }

        if (object != null) {
            this.javaScriptNamespaceInterfaces.put(namespace, object);
        }

    }

    public void removeJavascriptObject(String namespace) {
        if (namespace == null) {
            namespace = "";
        }

        this.javaScriptNamespaceInterfaces.remove(namespace);
    }

    public void disableJavascriptDialogBlock(boolean disable) {
        this.alertBoxBlock = !disable;
    }

    public void setWebChromeClient(WebChromeClient client) {
        this.webChromeClient = client;
    }

    public void clearCache(boolean includeDiskFiles) {
        super.clearCache(includeDiskFiles);
        CookieManager.getInstance().removeAllCookie();
        Context context = this.getContext();

        try {
            context.deleteDatabase("webview.db");
            context.deleteDatabase("webviewCache.db");
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        File appCacheDir = new File(this.APP_CACHE_DIRNAME);
        File webviewCacheDir = new File(context.getCacheDir().getAbsolutePath() + "/webviewCache");
        if (webviewCacheDir.exists()) {
            this.deleteFile(webviewCacheDir);
        }

        if (appCacheDir.exists()) {
            this.deleteFile(appCacheDir);
        }

    }

    public void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();

                for (int i = 0; i < files.length; ++i) {
                    this.deleteFile(files[i]);
                }
            }

            file.delete();
        } else {
            Log.e("Webview", "delete file no exists " + file.getAbsolutePath());
        }

    }

    private void runOnMainThread(Runnable runnable) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            runnable.run();
        } else {
            this.mainHandler.post(runnable);
        }
    }

    private class CallInfo {
        public String data = null;
        public int callbackId;
        public String method;

        public CallInfo(String handlerName, int id, Object[] args) {
            if (args == null) {
                args = new Object[0];
            }

            this.data = (new JSONArray(Arrays.asList(args))).toString();
            this.callbackId = id;
            this.method = handlerName;
        }

        public String toString() {
            JSONObject jo = new JSONObject();

            try {
                jo.put("method", this.method);
                jo.put("callbackId", this.callbackId);
                jo.put("data", this.data);
            } catch (JSONException var3) {
                var3.printStackTrace();
            }

            return jo.toString();
        }
    }

    /**
     * @deprecated
     */
    @Deprecated
    public interface FileChooser {
        @TargetApi(11)
        void openFileChooser(ValueCallback var1, String var2);

        @TargetApi(16)
        void openFileChooser(ValueCallback<Uri> var1, String var2, String var3);
    }

    public interface JavascriptCloseWindowListener {
        boolean onClose();
    }

    class InnerJavascriptInterface {
        InnerJavascriptInterface() {
        }

        private void PrintDebugInfo(String error) {
            Log.d("dsBridge", error);
            if (DWebView.isDebug) {
                DWebView.this.evaluateJavascript(String.format("alert('%s')", "DEBUG ERR MSG:\\n" + error.replaceAll("\\'", "\\\\'")));
            }

        }

        @JavascriptInterface
        @Keep
        public String call(String methodName, String argStr) {
            String error = "Js bridge  called, but can't find a corresponded JavascriptInterface object , please check your code!";
            String[] nameStr = DWebView.this.parseNamespace(methodName.trim());
            methodName = nameStr[1];
            Object jsb = DWebView.this.javaScriptNamespaceInterfaces.get(nameStr[0]);
            JSONObject ret = new JSONObject();

            try {
                ret.put("code", -1);
            } catch (JSONException var17) {
                var17.printStackTrace();
            }

            if (jsb == null) {
                this.PrintDebugInfo(error);
                return ret.toString();
            } else {
                Object arg = null;
                Method method = null;
                String callback = null;
                try {
                    JSONObject args = new JSONObject(argStr);
                    if (args.has("_dscbstub")) {
                        callback = args.getString("_dscbstub");
                    }

                    if (args.has("data")) {
                        arg = args.get("data");
                    }
                } catch (JSONException var19) {
                    error = String.format("The argument of \"%s\" must be a JSON object string!", methodName);
                    this.PrintDebugInfo(error);
                    var19.printStackTrace();
                    return ret.toString();
                }

                Class<?> cls = jsb.getClass();
                boolean asyn = false;

                try {
                    method = cls.getMethod(methodName, Object.class, CompletionHandler.class);
                    asyn = true;
                } catch (Exception var16) {
                    try {
                        method = cls.getMethod(methodName, Object.class);
                    } catch (Exception var15) {
                    }
                }

                if (method == null) {
                    error = "Not find method \"" + methodName + "\" implementation! please check if the  signature or namespace of the method is right ";
                    this.PrintDebugInfo(error);
                    return ret.toString();
                } else {
                    JavascriptInterface annotation = (JavascriptInterface) method.getAnnotation(JavascriptInterface.class);
                    if (annotation == null) {
                        error = "Method " + methodName + " is not invoked, since  it is not declared with JavascriptInterface annotation! ";
                        this.PrintDebugInfo(error);
                        return ret.toString();
                    } else {
                        method.setAccessible(true);

                        try {
                            if (!asyn) {
                                Object retData = method.invoke(jsb, arg);
                                ret.put("code", 0);
                                ret.put("data", retData);
                                return ret.toString();
                            }
                            final String cb = callback;
                            method.invoke(jsb, arg, new CompletionHandler() {
                                public void complete(Object retValue) {
                                    this.complete(retValue, true);
                                }

                                public void complete() {
                                    this.complete((Object) null, true);
                                }

                                public void setProgressData(Object value) {
                                    this.complete(value, false);
                                }

                                private void complete(Object retValue, boolean complete) {
                                    try {
                                        JSONObject ret = new JSONObject();
                                        ret.put("code", 0);
                                        ret.put("data", retValue);
                                        if (cb != null) {
                                            String script = String.format("%s(%s.data);", cb, ret.toString());
                                            if (complete) {
                                                script = script + "delete window." + cb;
                                            }

                                            DWebView.this.evaluateJavascript(script);
                                        }
                                    } catch (Exception var5) {
                                        var5.printStackTrace();
                                    }

                                }
                            });
                        } catch (Exception var18) {
                            var18.printStackTrace();
                            error = String.format("Call failed：The parameter of \"%s\" in Java is invalid.", methodName);
                            this.PrintDebugInfo(error);
                            return ret.toString();
                        }

                        return ret.toString();
                    }
                }
            }
        }
    }

}
